<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Lixunguan\Yuntongxun\Sdk as Yuntongxun;
use App\Model\TempPhone;
use Gregwar\Captcha\CaptchaBuilder;

class Common extends Controller
{
    public function sendPhoneMsg(request $request,$code='',$templateId=1)
    {
    	// $phone=$request->input['phone'];
    	$phone  = $request->input('phone');
    	// dd($phone2);
    	$sdk = new Yuntongxun(env('RONG_APP_ID'), env('RONG_ACCOUNT_SID'), env('RONG_AUTH_TOKEN'));


    	$code = '';
		// 生成随机验证码
		$charset = '123456789';
		$_len = strlen($charset) - 1;
			for ($i = 0;$i < 6;++$i) {
			    $code .= $charset[mt_rand(1, $_len)];
			}
		

    	// 1是短信模板， 1858842345为手机号, 第二个参数为发送的短信验证码
		$sms = $sdk->sendTemplateSMS($phone, array($code,30), $templateId);

		// 验证码储存在TempPhone表
		$bool = TempPhone::insertGetId([
			'code'=>$code,
			'phone'=>$phone,
			'time'=>time(),

			]);


    }

      public function buildCode(Request $request)
  	{
	    $builder = new CaptchaBuilder;
	    $builder->build();

	    //获取验证码内容
	    $phrase = $builder->getPhrase();
	    //将验证码存到session
	     // $request->session()->put('code', $phrase);
	    $request->session()->flash('code', $phrase);
	    //  \Session::save();
	    //生成图片
	    header("Cache-Control: no-cache, must-revalidate");
	    header('Content-Type: image/jpeg');
	    $builder->output();
	    exit;
	 }

	  //验证码验证
	public  static function CheckCode (Request $request, $formCodeName = 'code')
	{
		$userCode = $request->input($formCodeName);
			if ( $request->session()->get('code') == $userCode ) {
			   return	true;
			}
			return false;
	}
}
